library(sandwich)
library(lmtest)
set.seed(02138)
tw <- read.csv("tw-replication-dvn.csv", stringsAsFactors = FALSE, header = TRUE)

tw$favor_binary <- 1 * (tw$favor_attack %in% 1:2)

dem_mod <- lm(favor_binary ~ dem_dummy, data = tw)
summary(dem_mod)
confint(dem_mod)


mil_mod <- lm(favor_binary ~ mil_dummy, data = tw)
summary(mil_mod)
confint(mil_mod)

trade_mod <- lm(favor_binary ~ trade_dummy, data = tw)
summary(trade_mod)
confint(trade_mod)

threat_mod <- lm(favor_binary ~ threat_dummy, data = tw)
summary(threat_mod)
confint(threat_mod)


dem_inter_mod <- lm(favor_binary ~ dem_dummy * I(1-threat_dummy), data = tw)
summary(dem_inter_mod)
confint(dem_inter_mod)
coeftest(dem_inter_mod, vcov = vcovHC(dem_inter_mod))

nrow(model.matrix(dem_inter_mod))

boots <- 5000
hold <- matrix(NA, nrow = boots, ncol = length(coef(dem_inter_mod)))
for (b in seq_len(boots)) {
  tw.star <- tw[sample(1:nrow(tw), replace = TRUE),]
  hold[b,] <- coef(lm(favor_binary ~ dem_dummy * I(1-threat_dummy), data = tw.star))
}

ate <- hold[,2] + hold[,4]
ci.95 <- t(apply(hold, 2, quantile, probs = c(0.025, 0.975)))
ci.90 <- t(apply(hold, 2, quantile, probs = c(0.05, 0.95)))

cairo_pdf(file = "tw-replication.pdf",width = 5, height = 3, pointsize = 10)
par(mar = c(4.1, 0.1, 2.1, 0.1))
plot(x = NULL, y = NULL, xlim = c(-0.25, 0.25), ylim = c(0, 6), yaxt = "n", bty = "n", ylab = "", main = "", xlab = "Effect on Supporting Preemptive Strike")
abline(v = 0, col = "grey50", lty = 2)
points(x = colMeans(hold)[c(2,4)], y = c(3, 5), pch = 19)
segments(y0 = c(3,5), x0 = ci.95[c(2,4), 1], x1 = ci.95[c(2,4), 2])
segments(y0 = c(3,5), x0 = ci.90[c(2,4), 1], x1 = ci.90[c(2,4), 2], lwd = 2)
points(x = mean(ate), y = 1, pch = 19)
segments(y0 = 1, x0 = quantile(ate, probs = 0.025), x1 = quantile(ate, 0.975))
segments(y0 = 1, x0 = quantile(ate, probs = 0.05), x1 = quantile(ate, 0.95), lwd = 2)
text(x = -0.01, y = 5, "Eliminated Effect = ATE - ACDE", pos = 2)
text(x = 0.25, y = 3, "Effect of Democracy \n Fixing Threat (ACDE)", pos = 2)
text(x = 0.25, y = 1, "Effect of Democracy \n without Fixing Threat (ATE)", pos = 2)
dev.off()
